from functools import wraps

from flask import render_template, request, flash, redirect, url_for, session
from flask_login import login_required, current_user, login_user, logout_user

from app import app,login_manager
from app.model import *
from flask import jsonify, request
from db import db
import uuid
from flask import render_template


@app.route('/service/insert', methods=['POST'])
def insert_service():
    print("----------------insert_service---------------------")
    s_list = request.json.get("s_list", [])
    s_objs = [Service(
        service_id=uuid.uuid4(),
        equipment_id=data.get('equipment_id'),
        sequence_id=data.get('sequence_id'),
        maintenance_date=data.get('maintenance_date'),
        maintenance_content=data.get('maintenance_content'),
        change_configuration=data.get('change_configuration'),
        maintenance_count=data.get('maintenance_count'),
        maintenance_person=data.get('maintenance_person'),
        remark=data.get('remark'),
    ) for data in s_list]
    db.session.add_all(s_objs)
    try:
        db.session.commit()
        return jsonify({
            'msg': '插入成功'
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({"error": str(e)}), 400


# @app.route('/service', methods=['GET'])
def get_service():
    print("----------------get_service---------------------")
    service_id = request.args.get('service_id')
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)

    if service_id:
        services = Service.query.filter_by(service_id=service_id).paginate(page=page, per_page=per_page)
    else:
        services = Service.query.paginate(page=page, per_page=per_page)
    eq_list = []
    eq_f_list = []
    for obj in services.items:
        eq = Equipment.query.filter_by(equipment_id=obj.equipment_id).first()
        if eq:
            eq_list.append(eq.get())
        eq_f = Equipment_fault.query.filter_by(sequence_id=obj.sequence_id).first()
        if eq_f:
            eq_f_list.append(eq_f.get())
    service_data = [eq.get() for eq in services.items]
    return {
        "s_list": service_data,
        "eq_list": eq_list,
        'eq_f_list': eq_f_list,
        'total': services.total,
        'pages': services.pages,
        'status': 200,
    }
